<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

import IntelligentTemplateModal from './IntelligentTemplateModal.vue';
// 导入模态框组件
import LabTestModal from './LabTestModal.vue';
import PrescriptionModal from './PrescriptionModal.vue';
import SurgeryModal from './SurgeryModal.vue';
import TreatmentModal from './TreatmentModal.vue';

interface Props {
  pet?: any;
  record?: any;
  formData?: any;
}

interface Emits {
  (e: 'save', record: any): void;
  (e: 'saveDraft'): void;
  (e: 'preview'): void;
  (e: 'print'): void;
  (e: 'formDataChange', formData: any): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const recordNumber = ref(
  `NO${dayjs().format('YYYYMMDD')}${String(Math.floor(Math.random() * 10_000)).padStart(4, '0')}`,
);

// 表单数据
const formData = ref({
  recordDate: dayjs(),
  doctor: '',
  chiefComplaint: '',
  temperature: null,
  weight: null,
  respiration: null,
  heartRate: null,
  examination: {
    earsEyesMouthNose: 'normal',
    bonesMuscles: 'normal',
    skinCoat: 'normal',
    lymphNodes: 'normal',
    heartLungs: 'normal',
    abdominalPalpation: 'normal',
  },
  labTests: [],
  diagnosis: '',
  treatmentPlan: '',
  prescriptions: [],
  surgeries: [],
  treatments: [],
  doctorAdvice: '',
  precautions: '',
  followUpDate: null,
});

// 模态框状态
const modals = ref({
  labTest: false,
  prescription: false,
  surgery: false,
  treatment: false,
  intelligentTemplate: false,
});

// 快捷日期相关
const selectedQuickDate = ref<string>('');

// 表格列定义
const labTestColumns = [
  { title: '项目名称', dataIndex: 'name', key: 'name' },
  { title: '价格', dataIndex: 'price', key: 'price', width: 100 },
  { title: '操作', key: 'action', width: 80 },
];

const prescriptionColumns = [
  { title: '编组', dataIndex: 'group', key: 'group', width: 80 },
  { title: '名称', dataIndex: 'name', key: 'name' },
  {
    title: '规格',
    dataIndex: 'specification',
    key: 'specification',
    width: 120,
  },
  { title: '单位', dataIndex: 'unit', key: 'unit', width: 80 },
  { title: '用法', dataIndex: 'usage', key: 'usage', width: 100 },
  { title: '用量', dataIndex: 'dosage', key: 'dosage', width: 80 },
  { title: '单价', dataIndex: 'unitPrice', key: 'unitPrice', width: 100 },
  { title: '数量', dataIndex: 'quantity', key: 'quantity', width: 80 },
  { title: '添加人', dataIndex: 'addedBy', key: 'addedBy', width: 100 },
  { title: '备注', dataIndex: 'remarks', key: 'remarks', width: 120 },
  { title: '操作', key: 'action', width: 80 },
];

const surgeryColumns = [
  { title: '手术名称', dataIndex: 'name', key: 'name' },
  { title: '手术医生', dataIndex: 'surgeon', key: 'surgeon', width: 100 },
  {
    title: '麻醉师',
    dataIndex: 'anesthesiologist',
    key: 'anesthesiologist',
    width: 100,
  },
  {
    title: '手术日期',
    dataIndex: 'surgeryDate',
    key: 'surgeryDate',
    width: 120,
  },
  { title: '价格', dataIndex: 'price', key: 'price', width: 100 },
  { title: '操作', key: 'action', width: 80 },
];

const treatmentColumns = [
  { title: '处置名称', dataIndex: 'name', key: 'name' },
  { title: '护士', dataIndex: 'nurse', key: 'nurse', width: 100 },
  { title: '处置室', dataIndex: 'room', key: 'room', width: 100 },
  {
    title: '处置日期',
    dataIndex: 'treatmentDate',
    key: 'treatmentDate',
    width: 120,
  },
  { title: '价格', dataIndex: 'price', key: 'price', width: 100 },
  { title: '操作', key: 'action', width: 80 },
];

// 计算属性
const labTestTotal = computed(() => {
  return formData.value.labTests.reduce((total, item) => total + item.price, 0);
});

const prescriptionTotal = computed(() => {
  return formData.value.prescriptions.reduce(
    (total, item) => total + (item.unitPrice || 0) * (item.quantity || 0),
    0,
  );
});

const surgeryTotal = computed(() => {
  return formData.value.surgeries.reduce(
    (total, item) => total + (item.price || 0),
    0,
  );
});

const treatmentTotal = computed(() => {
  return formData.value.treatments.reduce(
    (total, item) => total + (item.price || 0),
    0,
  );
});

const hasAnyTreatment = computed(() => {
  return (
    formData.value.labTests.length > 0 ||
    formData.value.prescriptions.length > 0 ||
    formData.value.surgeries.length > 0 ||
    formData.value.treatments.length > 0
  );
});

// 方法
const showLabTestModal = () => {
  modals.value.labTest = true;
};

const showPrescriptionModal = () => {
  modals.value.prescription = true;
};

const showIntelligentTemplate = () => {
  modals.value.intelligentTemplate = true;
};

const showSurgeryModal = () => {
  modals.value.surgery = true;
};

const showTreatmentModal = () => {
  modals.value.treatment = true;
};

const handleLabTestSuccess = (tests: any[]) => {
  formData.value.labTests = [...formData.value.labTests, ...tests];
  message.success('检验项目添加成功');
};

const handlePrescriptionSuccess = (prescriptions: any[]) => {
  formData.value.prescriptions = [
    ...formData.value.prescriptions,
    ...prescriptions,
  ];
  message.success('处方添加成功');
};

const handleTemplateSuccess = (template: any) => {
  formData.value.treatmentPlan = template.treatment;
  formData.value.diagnosis = template.diagnosis;
  formData.value.doctorAdvice = template.advice;
  message.success('智能模板应用成功');
};

const handleSurgerySuccess = (surgeries: any[]) => {
  formData.value.surgeries = [...formData.value.surgeries, ...surgeries];
  message.success('手术项目添加成功');
};

const handleTreatmentSuccess = (treatments: any[]) => {
  formData.value.treatments = [...formData.value.treatments, ...treatments];
  message.success('处置项目添加成功');
};

const removeLabTest = (index: number) => {
  formData.value.labTests.splice(index, 1);
};

const removePrescription = (index: number) => {
  formData.value.prescriptions.splice(index, 1);
};

const removeSurgery = (index: number) => {
  formData.value.surgeries.splice(index, 1);
};

const removeTreatment = (index: number) => {
  formData.value.treatments.splice(index, 1);
};

const saveRecord = () => {
  if (!formData.value.doctor) {
    message.warning('请选择主治医生');
    return;
  }

  if (!formData.value.chiefComplaint) {
    message.warning('请填写主诉');
    return;
  }

  if (!formData.value.diagnosis) {
    message.warning('请填写病情诊断');
    return;
  }

  // 更新现有病历记录，而不是创建新的
  const updatedRecord = {
    ...props.record, // 保留原有记录的ID和其他字段
    ...formData.value,
    totalAmount:
      labTestTotal.value +
      prescriptionTotal.value +
      surgeryTotal.value +
      treatmentTotal.value,
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  };

  emit('save', updatedRecord);
  message.success('病历保存成功！');
};

// 保存草稿
const saveDraft = () => {
  // 草稿不需要验证必填字段
  emit('saveDraft');
};

const previewRecord = () => {
  emit('preview');
};

const printRecord = () => {
  emit('print');
};

// 快捷日期相关方法
const setQuickDate = (type: string) => {
  selectedQuickDate.value = type;

  switch (type) {
    case 'custom': {
      // 自定义模式，不设置日期，让用户手动选择
      formData.value.followUpDate = null;
      break;
    }
    case 'nextMonth': {
      formData.value.followUpDate = dayjs().add(1, 'month');
      break;
    }
    case 'nextWeek': {
      formData.value.followUpDate = dayjs().add(1, 'week');
      break;
    }
    case 'today': {
      formData.value.followUpDate = dayjs();
      break;
    }
    case 'tomorrow': {
      formData.value.followUpDate = dayjs().add(1, 'day');
      break;
    }
  }
};

const isQuickDateSelected = (type: string): boolean => {
  if (!formData.value.followUpDate) return false;

  const selectedDate = formData.value.followUpDate;

  switch (type) {
    case 'custom': {
      // 如果不是预设的快捷日期，则认为是自定义
      return (
        !selectedDate.isSame(dayjs(), 'day') &&
        !selectedDate.isSame(dayjs().add(1, 'day'), 'day') &&
        !selectedDate.isSame(dayjs().add(1, 'week'), 'day') &&
        !selectedDate.isSame(dayjs().add(1, 'month'), 'day')
      );
    }
    case 'nextMonth': {
      return selectedDate.isSame(dayjs().add(1, 'month'), 'day');
    }
    case 'nextWeek': {
      return selectedDate.isSame(dayjs().add(1, 'week'), 'day');
    }
    case 'today': {
      return selectedDate.isSame(dayjs(), 'day');
    }
    case 'tomorrow': {
      return selectedDate.isSame(dayjs().add(1, 'day'), 'day');
    }
    default: {
      return false;
    }
  }
};

const onDateChange = (date: any) => {
  // 当用户手动选择日期时，更新快捷日期状态
  if (date) {
    // 检查是否匹配任何快捷日期
    if (date.isSame(dayjs(), 'day')) {
      selectedQuickDate.value = 'today';
    } else if (date.isSame(dayjs().add(1, 'day'), 'day')) {
      selectedQuickDate.value = 'tomorrow';
    } else if (date.isSame(dayjs().add(1, 'week'), 'day')) {
      selectedQuickDate.value = 'nextWeek';
    } else if (date.isSame(dayjs().add(1, 'month'), 'day')) {
      selectedQuickDate.value = 'nextMonth';
    } else {
      selectedQuickDate.value = 'custom';
    }
  } else {
    selectedQuickDate.value = '';
  }
};

// 监听宠物变化，重置表单
watch(
  () => props.pet,
  (newPet) => {
    if (newPet) {
      // 如果有传入的formData，使用传入的数据
      if (props.formData) {
        // 确保所有必需的数组字段都存在
        formData.value = {
          recordDate: dayjs(),
          doctor: '',
          chiefComplaint: '',
          temperature: null,
          weight: null,
          respiration: null,
          heartRate: null,
          examination: {
            earsEyesMouthNose: 'normal',
            bonesMuscles: 'normal',
            skinCoat: 'normal',
            lymphNodes: 'normal',
            heartLungs: 'normal',
            abdominalPalpation: 'normal',
          },
          labTests: [],
          diagnosis: '',
          treatmentPlan: '',
          prescriptions: [],
          surgeries: [],
          treatments: [],
          doctorAdvice: '',
          precautions: '',
          followUpDate: null,
          ...props.formData, // 使用传入的数据覆盖默认值
        };
      } else {
        // 重置表单数据
        formData.value = {
          recordDate: dayjs(),
          doctor: '',
          chiefComplaint: '',
          temperature: null,
          weight: null,
          respiration: null,
          heartRate: null,
          examination: {
            earsEyesMouthNose: 'normal',
            bonesMuscles: 'normal',
            skinCoat: 'normal',
            lymphNodes: 'normal',
            heartLungs: 'normal',
            abdominalPalpation: 'normal',
          },
          labTests: [],
          diagnosis: '',
          treatmentPlan: '',
          prescriptions: [],
          surgeries: [],
          treatments: [],
          doctorAdvice: '',
          precautions: '',
          followUpDate: null,
        };
      }
      recordNumber.value = `NO${dayjs().format('YYYYMMDD')}${String(Math.floor(Math.random() * 10_000)).padStart(4, '0')}`;
    }
  },
  { immediate: true },
);

// 监听formData变化，同步更新本地表单数据
let isInternalUpdate = false;
watch(
  () => props.formData,
  (newFormData) => {
    if (newFormData && !isInternalUpdate) {
      isInternalUpdate = true;
      // 确保所有必需的数组字段都存在
      formData.value = {
        recordDate: dayjs(),
        doctor: '',
        chiefComplaint: '',
        temperature: null,
        weight: null,
        respiration: null,
        heartRate: null,
        examination: {
          earsEyesMouthNose: 'normal',
          bonesMuscles: 'normal',
          skinCoat: 'normal',
          lymphNodes: 'normal',
          heartLungs: 'normal',
          abdominalPalpation: 'normal',
        },
        labTests: [],
        diagnosis: '',
        treatmentPlan: '',
        prescriptions: [],
        surgeries: [],
        treatments: [],
        doctorAdvice: '',
        precautions: '',
        followUpDate: null,
        ...newFormData, // 使用传入的数据覆盖默认值
      };
      nextTick(() => {
        isInternalUpdate = false;
      });
    }
  },
  { deep: true },
);
</script>

<template>
  <div class="medical-record-form">
    <div class="record-header">
      <div class="record-title">
        <h3>病历 (编号: {{ recordNumber }})</h3>
      </div>
      <div class="record-actions">
        <a-button @click="previewRecord">预览</a-button>
        <a-button @click="printRecord">打印</a-button>
        <a-button @click="saveDraft">保存草稿</a-button>
        <a-button type="primary" @click="saveRecord">保存病历</a-button>
      </div>
    </div>

    <!-- 竖排结构 - 所有步骤默认展开 -->
    <div class="record-content">
      <!-- 基本信息 -->
      <div class="section">
        <div class="section-header">
          <h4>📋 基本信息</h4>
        </div>
        <div class="section-content">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="病历日期">
                <a-date-picker
                  v-model:value="formData.recordDate"
                  format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="主治医生">
                <a-select
                  v-model:value="formData.doctor"
                  placeholder="选择医生"
                  style="width: 100%"
                >
                  <a-select-option value="孙医生">孙医生</a-select-option>
                  <a-select-option value="李医生">李医生</a-select-option>
                  <a-select-option value="张医生">张医生</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="宠物信息">
                <span v-if="pet">{{ pet.name }} ({{ pet.ownerName }})</span>
                <span v-else class="text-muted">未选择宠物</span>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
      </div>

      <!-- 主诉 -->
      <div class="section">
        <div class="section-header">
          <h4>🏥 主诉</h4>
        </div>
        <div class="section-content">
          <a-form-item label="主诉记录">
            <a-textarea
              v-model:value="formData.chiefComplaint"
              placeholder="请输入病宠主人主诉病情......"
              :rows="4"
            />
          </a-form-item>
        </div>
      </div>

      <!-- 体检检查 -->
      <div class="section">
        <div class="section-header">
          <h4>🔍 体检检查</h4>
        </div>
        <div class="section-content">
          <a-row :gutter="16">
            <a-col :span="6">
              <a-form-item label="体温">
                <a-input-number
                  v-model:value="formData.temperature"
                  :min="30"
                  :max="45"
                  :precision="1"
                  addon-after="°C"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="体重">
                <a-input-number
                  v-model:value="formData.weight"
                  :min="0"
                  :max="100"
                  :precision="1"
                  addon-after="kg"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="呼吸">
                <a-input-number
                  v-model:value="formData.respiration"
                  :min="0"
                  :max="200"
                  addon-after="次/分"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="心率">
                <a-input-number
                  v-model:value="formData.heartRate"
                  :min="0"
                  :max="300"
                  addon-after="次/分"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <!-- 临床检查 -->
          <div class="clinical-examination">
            <h5>临床检查</h5>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="耳/眼/口/鼻">
                  <a-radio-group
                    v-model:value="formData.examination.earsEyesMouthNose"
                  >
                    <a-radio value="normal">正常</a-radio>
                    <a-radio value="abnormal">异常</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="骨骼/肌肉">
                  <a-radio-group
                    v-model:value="formData.examination.bonesMuscles"
                  >
                    <a-radio value="normal">正常</a-radio>
                    <a-radio value="abnormal">异常</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="皮肤/皮毛">
                  <a-radio-group v-model:value="formData.examination.skinCoat">
                    <a-radio value="normal">正常</a-radio>
                    <a-radio value="abnormal">异常</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="体表淋巴结">
                  <a-radio-group
                    v-model:value="formData.examination.lymphNodes"
                  >
                    <a-radio value="normal">正常</a-radio>
                    <a-radio value="abnormal">异常</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="心脏/肺脏">
                  <a-radio-group
                    v-model:value="formData.examination.heartLungs"
                  >
                    <a-radio value="normal">正常</a-radio>
                    <a-radio value="abnormal">异常</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="触诊腹腔">
                  <a-radio-group
                    v-model:value="formData.examination.abdominalPalpation"
                  >
                    <a-radio value="normal">正常</a-radio>
                    <a-radio value="abnormal">异常</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
      </div>

      <!-- 主观诊断 -->
      <div class="section">
        <div class="section-header">
          <h4>💊 主观诊断</h4>
        </div>
        <div class="section-content">
          <a-form-item label="病情诊断">
            <a-textarea
              v-model:value="formData.diagnosis"
              placeholder="请输入病情诊断......"
              :rows="4"
            />
          </a-form-item>
          <a-form-item label="治疗方案">
            <div class="treatment-plan-section">
              <a-button type="primary" @click="showIntelligentTemplate">
                使用智能模板快速添加
              </a-button>
              <a-textarea
                v-model:value="formData.treatmentPlan"
                placeholder="请输入治疗方案......"
                :rows="4"
                style="margin-top: 12px"
              />
            </div>
          </a-form-item>
        </div>
      </div>

      <!-- 治疗方案 -->
      <div class="section">
        <div class="section-header">
          <h4>💊 治疗方案</h4>
          <div class="treatment-actions">
            <a-button type="primary" @click="showLabTestModal">+ 检验</a-button>
            <a-button type="primary" @click="showPrescriptionModal">
              + 处方
            </a-button>
            <a-button type="primary" @click="showSurgeryModal">+ 手术</a-button>
            <a-button type="primary" @click="showTreatmentModal">
              + 处置
            </a-button>
          </div>
        </div>
        <div class="section-content">
          <!-- 检验项目 -->
          <div class="treatment-group" v-if="formData.labTests.length > 0">
            <div class="group-header">
              <h5>🧪 检验项目</h5>
            </div>
            <a-table
              :columns="labTestColumns"
              :data-source="formData.labTests"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'price'">
                  ¥{{ record.price.toFixed(2) }}
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button
                    type="text"
                    danger
                    size="small"
                    @click="removeLabTest(index)"
                  >
                    删除
                  </a-button>
                </template>
              </template>
            </a-table>
            <div class="group-total">
              <span>检验总计: ¥{{ labTestTotal.toFixed(2) }}</span>
            </div>
          </div>

          <!-- 处方项目 -->
          <div class="treatment-group" v-if="formData.prescriptions.length > 0">
            <div class="group-header">
              <h5>💊 处方项目</h5>
            </div>
            <a-table
              :columns="prescriptionColumns"
              :data-source="formData.prescriptions"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'unitPrice'">
                  ¥{{ (record.unitPrice || 0).toFixed(2) }}
                </template>
                <template v-else-if="column.key === 'totalPrice'">
                  ¥{{
                    ((record.unitPrice || 0) * (record.quantity || 0)).toFixed(
                      2,
                    )
                  }}
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button
                    type="text"
                    danger
                    size="small"
                    @click="removePrescription(index)"
                  >
                    删除
                  </a-button>
                </template>
              </template>
            </a-table>
            <div class="group-total">
              <span>处方总计: ¥{{ prescriptionTotal.toFixed(2) }}</span>
            </div>
          </div>

          <!-- 手术项目 -->
          <div class="treatment-group" v-if="formData.surgeries.length > 0">
            <div class="group-header">
              <h5>🔪 手术项目</h5>
            </div>
            <a-table
              :columns="surgeryColumns"
              :data-source="formData.surgeries"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'price'">
                  ¥{{ (record.price || 0).toFixed(2) }}
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button
                    type="text"
                    danger
                    size="small"
                    @click="removeSurgery(index)"
                  >
                    删除
                  </a-button>
                </template>
              </template>
            </a-table>
            <div class="group-total">
              <span>手术总计: ¥{{ surgeryTotal.toFixed(2) }}</span>
            </div>
          </div>

          <!-- 处置项目 -->
          <div class="treatment-group" v-if="formData.treatments.length > 0">
            <div class="group-header">
              <h5>🩺 处置项目</h5>
            </div>
            <a-table
              :columns="treatmentColumns"
              :data-source="formData.treatments"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'price'">
                  ¥{{ (record.price || 0).toFixed(2) }}
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button
                    type="text"
                    danger
                    size="small"
                    @click="removeTreatment(index)"
                  >
                    删除
                  </a-button>
                </template>
              </template>
            </a-table>
            <div class="group-total">
              <span>处置总计: ¥{{ treatmentTotal.toFixed(2) }}</span>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="!hasAnyTreatment" class="empty-treatment">
            <div class="empty-icon">💊</div>
            <div class="empty-text">暂无治疗方案，请点击上方按钮添加</div>
          </div>
        </div>
      </div>

      <!-- 医嘱 -->
      <div class="section">
        <div class="section-header">
          <h4>📝 医嘱</h4>
        </div>
        <div class="section-content">
          <a-form-item label="医嘱内容">
            <a-textarea
              v-model:value="formData.doctorAdvice"
              placeholder="请输入医嘱内容......"
              :rows="6"
            />
          </a-form-item>
          <a-form-item label="注意事项">
            <a-textarea
              v-model:value="formData.precautions"
              placeholder="请输入注意事项......"
              :rows="4"
            />
          </a-form-item>
          <a-form-item label="复诊安排">
            <div class="follow-up-section">
              <div class="quick-dates">
                <a-button
                  size="small"
                  @click="setQuickDate('today')"
                  :type="isQuickDateSelected('today') ? 'primary' : 'default'"
                >
                  今天
                </a-button>
                <a-button
                  size="small"
                  @click="setQuickDate('tomorrow')"
                  :type="
                    isQuickDateSelected('tomorrow') ? 'primary' : 'default'
                  "
                >
                  明天
                </a-button>
                <a-button
                  size="small"
                  @click="setQuickDate('nextWeek')"
                  :type="
                    isQuickDateSelected('nextWeek') ? 'primary' : 'default'
                  "
                >
                  下周
                </a-button>
                <a-button
                  size="small"
                  @click="setQuickDate('nextMonth')"
                  :type="
                    isQuickDateSelected('nextMonth') ? 'primary' : 'default'
                  "
                >
                  下月
                </a-button>
                <a-button
                  size="small"
                  @click="setQuickDate('custom')"
                  :type="isQuickDateSelected('custom') ? 'primary' : 'default'"
                >
                  自定义
                </a-button>
              </div>
              <a-date-picker
                v-model:value="formData.followUpDate"
                format="YYYY-MM-DD"
                placeholder="选择复诊日期"
                style="width: 100%; margin-top: 8px"
                @change="onDateChange"
              />
            </div>
          </a-form-item>
        </div>
      </div>

      <!-- 费用汇总 -->
      <div class="section">
        <div class="section-header">
          <h4>💰 费用汇总</h4>
        </div>
        <div class="section-content">
          <a-row :gutter="16">
            <a-col :span="6">
              <div class="cost-item">
                <span class="cost-label">检验费用:</span>
                <span class="cost-value">¥{{ labTestTotal.toFixed(2) }}</span>
              </div>
            </a-col>
            <a-col :span="6">
              <div class="cost-item">
                <span class="cost-label">处方费用:</span>
                <span class="cost-value"
                  >¥{{ prescriptionTotal.toFixed(2) }}</span
                >
              </div>
            </a-col>
            <a-col :span="6">
              <div class="cost-item">
                <span class="cost-label">手术费用:</span>
                <span class="cost-value">¥{{ surgeryTotal.toFixed(2) }}</span>
              </div>
            </a-col>
            <a-col :span="6">
              <div class="cost-item">
                <span class="cost-label">处置费用:</span>
                <span class="cost-value">¥{{ treatmentTotal.toFixed(2) }}</span>
              </div>
            </a-col>
          </a-row>
          <a-row :gutter="16" style="margin-top: 12px">
            <a-col :span="24">
              <div class="cost-item total">
                <span class="cost-label">总计:</span>
                <span class="cost-value"
                  >¥{{
                    (
                      labTestTotal +
                      prescriptionTotal +
                      surgeryTotal +
                      treatmentTotal
                    ).toFixed(2)
                  }}</span
                >
              </div>
            </a-col>
          </a-row>
        </div>
      </div>
    </div>

    <!-- 模态框组件 -->
    <LabTestModal
      v-model:visible="modals.labTest"
      @success="handleLabTestSuccess"
    />
    <PrescriptionModal
      v-model:visible="modals.prescription"
      @success="handlePrescriptionSuccess"
    />
    <IntelligentTemplateModal
      v-model:visible="modals.intelligentTemplate"
      :diagnosis="formData.diagnosis"
      @success="handleTemplateSuccess"
    />
    <SurgeryModal
      v-model:visible="modals.surgery"
      @success="handleSurgerySuccess"
    />
    <TreatmentModal
      v-model:visible="modals.treatment"
      @success="handleTreatmentSuccess"
    />
  </div>
</template>

<style scoped>
/* 打印样式 */
@media print {
  .medical-record-form {
    border: none;
    box-shadow: none;
  }

  .record-actions {
    display: none;
  }

  .section {
    margin-bottom: 16px;
    break-inside: avoid;
  }

  .section-header {
    background: #f0f0f0 !important;
  }
}

.medical-record-form {
  display: flex;
  flex-direction: column;
  min-height: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.record-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.record-title h3 {
  margin: 0;
  color: #262626;
}

.record-actions {
  display: flex;
  gap: 8px;
}

.record-content {
  flex: 1;
  padding: 24px;
  overflow-y: visible;
}

.section {
  margin-bottom: 24px;
  overflow: hidden;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.section-content {
  padding: 16px;
}

.clinical-examination h5 {
  margin: 16px 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #666;
}

.lab-tests-section,
.prescription-section {
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.total-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 12px;
  margin-top: 16px;
  font-weight: 600;
  border-top: 1px solid #f0f0f0;
}

.payment-status {
  color: #f5222d;
}

.treatment-plan-section {
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.cost-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background: #fafafa;
  border-radius: 4px;
}

.cost-item.total {
  font-weight: 600;
  background: #e6f7ff;
}

.cost-label {
  color: #666;
}

.cost-value {
  font-weight: 600;
  color: #262626;
}

.text-muted {
  color: #999;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background: #fafafa;
}

.treatment-actions {
  display: flex;
  gap: 8px;
}

.treatment-group {
  margin-bottom: 24px;
  overflow: hidden;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.group-header {
  padding: 12px 16px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.group-header h5 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.group-total {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 12px 16px;
  font-weight: 600;
  background: #fafafa;
  border-top: 1px solid #f0f0f0;
}

.empty-treatment {
  padding: 40px 20px;
  color: #999;
  text-align: center;
}

.empty-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.empty-text {
  font-size: 16px;
}

/* 快捷日期样式 */
.follow-up-section {
  width: 100%;
}

.quick-dates {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 8px;
}

.quick-dates .ant-btn {
  height: 28px;
  padding: 0 12px;
  font-size: 12px;
  border-radius: 4px;
}

.quick-dates .ant-btn-primary {
  background: #1890ff;
  border-color: #1890ff;
}

.quick-dates .ant-btn-default {
  color: #666;
  border-color: #d9d9d9;
}

.quick-dates .ant-btn-default:hover {
  color: #1890ff;
  border-color: #1890ff;
}

/* 病历头部样式 */
.record-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  margin-bottom: 24px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.record-title {
  flex: 1;
}

.record-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.record-actions {
  display: flex;
  gap: 8px;
}
</style>
